//
//  FFRecvRecordVM.m
//  LLWallet
//
//  Created by tt on 2020/12/18.
//

#import "FFRecvRecordVM.h"
#import "FFRecvRecordCell.h"

@interface FFRecvRecordVM ()

@property(nonatomic,assign) BOOL hasMore;
@property(nonatomic,assign) NSInteger pageIndex;
@property(nonatomic,strong) NSMutableArray<FFRecvRecordResp*> *items;

@end

@implementation FFRecvRecordVM


- (NSArray<NSDictionary *> *)tableSectionMaps {
    if(self.items.count<=0) {
        return nil;
    }
    
    NSMutableArray *items = [NSMutableArray array];
    
    NSString *prePayDay;
    NSMutableArray *preItems = [NSMutableArray array];
    for (FFRecvRecordResp *resp in self.items) {
        if(!prePayDay || ![prePayDay isEqualToString:resp.payDay]) {
            prePayDay = resp.payDay;
            preItems = [NSMutableArray array];
            [items addObject:@{
                @"height":@(0.0f),
                @"title": resp.payDay,
                @"items":preItems,
            }];
        }
        
        [preItems addObject: @{
            @"class": FFRecvRecordModel.class,
            @"avatar": [WKAvatarUtil getAvatar:resp.uid],
            @"name": resp.name?:@"",
            @"time": resp.payTime?:@"",
            @"amount": @(resp.amount),
        }];
    }
    
    return items;
}

- (NSMutableArray<FFRecvRecordResp *> *)items {
    if(!_items) {
        _items = [NSMutableArray array];
    }
    return _items;
}

- (void)requestData:(void (^)(NSError * _Nullable))complete {
    __weak typeof(self) weakSelf = self;
    [[WKAPIClient sharedClient] GET:@"impay/recvpay/recv/record" parameters:@{@"page_index":@(self.pageIndex),@"page_size":@([WKApp shared].config.pageSize)} model:FFRecvRecordResp.class].then(^(NSArray<FFRecvRecordResp*> *items){
        [weakSelf.items addObjectsFromArray:items];
        if(items && items.count>=[WKApp shared].config.pageSize) {
            self.hasMore = true;
        }else {
            self.hasMore = false;
        }
         complete(nil);
       
    }).catch(^(NSError *error){
        complete(error);
    });
}


- (void)pullup:(void (^)(BOOL))complete {
    if(!self.hasMore) {
        complete(self.hasMore);
        return;
    }
    self.pageIndex ++;
    [self requestData:^(NSError * _Nullable error) {
        complete(self.hasMore);
    }];
}

- (BOOL)enablePullup {
    return YES;
}

@end

@implementation FFRecvRecordResp

+ (WKModel *)fromMap:(NSDictionary *)dictory type:(ModelMapType)type {
    FFRecvRecordResp *resp = [FFRecvRecordResp new];
    resp.uid = dictory[@"uid"]?:@"";
    resp.name = dictory[@"name"]?:@"";
    resp.payDay = dictory[@"pay_day"]?:@"";
    resp.payTime = dictory[@"pay_time"]?:@"";
    resp.amount = dictory[@"amount"]?[dictory[@"amount"] integerValue]:0;
    return resp;
}

@end
